<template>
  <div class="dialog">
    <el-dialog title="外层 Dialog" :visible="visible" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="资源路径" prop="url">
          <el-input v-model="form.url"></el-input>
        </el-form-item>
        <el-form-item prop="categoryId" label="资源分类">
            <el-select clearable v-model="form.categoryId">
              <el-option v-for="cate in categories" :key="cate.id" :label="cate.name" :value="cate.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
   </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { saveOrUpdate, getResource } from '@/services/resource'

export default Vue.extend({
  name: 'ResourceDialog',
  data () {
    return {
      form: {
        id: null,
        name: '',
        categoryId: '',
        url: '',
        description: ''
      },
      rules: {}
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editId: {
      type: Number || null,
      default: null
    },
    categories: {
      type: Array,
      default: () => []
    },
    closeDialog: { type: Function }
  },
  methods: {
    async onSubmit () {
      try {
        // 1. 表单验证
        await (this.$refs.form).validate()
        // 2. 验证通过 -> 提交表单
        const { data } = await saveOrUpdate(this.form)
        console.log(data)
        // 3. 处理请求结果
        if (data.code === '000000') {
          this.closeDialog()
          this.$message.success('提交成功')
        }
      } catch (err) {
        console.log('error submit!!')
        return false
      }
    },
    async loadInfo () {
      const { data } = await getResource(this.editId || null)
      console.log(data)
      if (data.data.menuInfo) {
        this.form = data.data.menuInfo
      }
      if (data.code === '000000') {
        const res = data.data
        this.form = {
          id: res.id,
          name: res.name,
          categoryId: res.categoryId,
          url: res.url,
          description: res.description
        }
      }
    }
  },
  created () {
    if (this.editId) {
      this.loadInfo()
    }
  }
})
</script>

<style lang="scss" scoped>

</style>
